package chen.bupt.slick

import scala.slick.driver.MySQLDriver.simple._
/**
 * Created by chenlingpeng on 2015/1/6.
 */
object SlickTest extends App{
  val db = Database.forConfig("mysql")
  implicit val session = db.createSession()
  import chen.bupt.slick.beans.Tables._
//  import scala.slick.driver.MySQLDriver.api._

  def selectTest() = {
    Groups.run.foreach{f=>println(f.id+"\t"+f.name)}
    Groups.filter{g => g.id =!= 1l}.foreach{f=>println(f.id+"\t"+f.name)}
    val res = for (g <- Task if g.id > 3l) yield g
    res.groupBy{case t => t.projectid}.map{case (projectid, tasks)=>
      (projectid, tasks.size)
    }.run.foreach{case (id, size)=>println(id+"\t"+size)}

    val q = Task.map{case t=>t.ctime}
    println(q.min.run)
    println(q.max.run)
    println(q.avg.run)
    println(q.sum.run)

    val subq = User.filter(_.id===1l).map(_.id)
    Task.filter(_.ownby in subq).run.foreach(t=>println(t.description))

  }

  def updateTest() = {
    var d = 1
    val q = for(task <- Task if task.id === 1264l) yield {
      task.state
    }
    val old = q.first
    println(q.updateStatement)
    println("affect row: "+q.update(old+1))
  }

  def deleteTest() = {
    val q = for(user <- User if user.id === 1l) yield user
//    q.run.foreach{case u => println(u.email)}
    println("affect row: "+q.delete)
  }

  def insertTest() = {
//    User += (123l,"name","email","password",2,Some(1l),2l)
//    val ret = User.map(u=>(u.name,u.email,u.password,u.role,u.groupid,u.teamid)) += ("name","email","password",2,Some(1l),2l)
//    println(ret)
//    println(User.insertStatement)
    val uid = (User.map(u=>(u.email, u.name, u.password, u.role, u.groupid,u.teamid)) returning User.map(_.id)) += ("","","",3,Some(3l),3l)
    println(uid.asInstanceOf[Long])
//    User += UserRow(3l,"","","",3,Some(5l),5l)
  }

//  updateTest()
//  updateTest()
//  println(new String(Base64.decodeBase64("MjI6MDE6ZTQ6ZTE6N2I6ZmEjMTQyMDUxNDMzNA==")))
  insertTest()
}
